<template>
  <div style="padding-bottom: 10px">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="matterName">
          <el-input style="width: 340px"
              v-model="queryParams.matterName"
              placeholder="事项名称"
              clearable
              @keyup.enter.native="handleQuery"
              suffix-icon="search"
              :suffix-icon-click="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="em5">
          <el-select v-model="queryParams.em5" placeholder="请选择是否催办" clearable style="width: 240px">
            <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="isFollow">
          <el-select v-model="queryParams.isFollow" placeholder="请选择是否关注" clearable style="width: 240px">
            <el-option v-for="item in options2" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
<!--      <el-form-item prop="isTimeOut">-->
<!--        <el-select v-model="queryParams.isFollowed" placeholder="请选择是否关注" clearable style="width: 240px">-->
<!--          <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item prop="isTimeOut">-->
<!--        <el-select v-model="queryParams.isDialog" placeholder="请选择是否催办" clearable style="width: 240px">-->
<!--          <el-option v-for="item in options3" :key="item.value" :label="item.label" :value="item.value"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="search" size="mini" @click="handleQuery">查询</el-button>
        <el-button icon="refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button type="success" style="margin-top:-10px;margin-bottom: 15px" @click="createMatter">创建事项</el-button>

    <el-table v-loading="loading" :data="matterList" @selection-change="handleSelectionChange">
      <el-table-column min-width="3%" type="index" label="序号" align="center"/>
        <el-table-column  min-width="10%" label="事项名称" prop="matterName">
          <template #default="{ row }">
            <el-text type="primary" style="cursor: pointer" @click="getInto(row)">{{ row.matterName }}</el-text>
          </template>
        </el-table-column>
        <el-table-column min-width="5%" label="当前进展" prop="workPrtKeyNode"/>
        <el-table-column min-width="6%" label="负责人" align="center" prop="matterResponsible"/>
        <el-table-column min-width="6%" label="关联人" align="center" prop="em2"/>
        <el-table-column min-width="8%" label="所属部门" align="center" prop="dept"/>
        <el-table-column min-width="6%" label="完成期限" align="center" prop="completionDeadline" :formatter="formatDate"/>
        <el-table-column min-width="5%" label="事项状态" align="center">
          <template #default="scope">
            <dict-tag :options="task_status" :value="scope.row.em4"/>
          </template>
        </el-table-column>
      <el-table-column min-width="10%" label="批示意见" align="center" prop="dialogContent">
        <template #default="scope">
          <span v-html="scope.row.dialogContent"></span>
        </template>
      </el-table-column>
        <el-table-column min-width="10%" label="催办状态" align="center" prop="dialogStatus">
          <template #default="scope">
            <el-tag v-if="scope.row.dialogStatus" type="success">已催办</el-tag>
            <el-tag v-else type="info">未催办</el-tag>
          </template>
        </el-table-column>
      <el-table-column min-width="5%" label="关注状态" align="center" prop="isFollowed">
        <template #default="scope">
          <el-tag v-if="scope.row.isFollowed" type="success">已关注</el-tag>
          <el-tag v-else type="info">未关注</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px">
        <template #default="scope">
          <!-- <el-button style="margin: 1px" size="mini" type="success" plain @click="getInto(scope.row)">进入</el-button> -->
          <!-- <el-button style="margin: 1px" size="mini" type="warning" plain @click="urgent(scope.row)">催办</el-button> -->
          <el-button plain type="primary" :disabled="getIsLeader(scope.row)" @click="viewMatter(scope.row)">落实</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />

   <!--  <el-pagination
        v-show="total > 0"
        :current-page.sync="queryParams.pageNum"
        :page-size.sync="queryParams.pageSize"
        :total="total"
        @current-change="handleCurrentChange"
        style="width: 97%; margin-top: 10px;"
        :pager-count="5"
    /> -->

    <el-dialog :before-close="handleClose" draggable overflow v-model="dialogFormVisible" title="催办:" width="500"
               style="padding: 50px">
      <el-form :model="urgentFrom">
        <el-form-item label-width="0px">
          <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 100 }" v-model="urgentFrom.dialogContent" autosize
                    autocomplete="off"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitDialog">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>

import {reactive, toRefs, onMounted, getCurrentInstance} from 'vue';
import {listMatter, dataScopeMatterList, updteIsKeyWork, addDialog, updateIsFollowed} from "@/api/matter/matter";
import {ElInput, ElSelect, ElOption, ElRow, ElCol, ElForm, ElFormItem, ElButton, ElMessageBox} from 'element-plus';
import router from "@/router";
export default {
  name: "taskReception",
  components: {
    ElInput,
    ElSelect,
    ElOption,
    ElRow,
    ElCol,
    ElForm,
    ElFormItem,
    ElButton,
    ElMessageBox,
  },
  setup(_, {emit}) {
    const {proxy} = getCurrentInstance();
    const {task_status} = proxy.useDict('task_status');
    const data = reactive({
      loading: false,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      matterList: [],
      title: "",
      open: false,
      isKeyWork: 1,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        isKeyWork: '', //是否重要工作
        isTimeOut: '', //是否超期
        isFollow: '', //是否关注
        keyWord: null, // 关键词
        matterName: '',
        em1: null,
        em2: null,
        em3: null,
        em4: null,
        em5: null,
      },
      options1: [
        {value: '', label: '全部'},
        {value: '0', label: '未催办'},
        {value: '1', label: '已催办'},
      ],
      options2: [
        {value: '', label: '全部'},
        {value: '0', label: '已关注'},
        {value: '1', label: '未关注'},
      ],
      options3: [
        {value: '', label: '全部'},
        {value: false, label: '否'},
        {value: true, label: '是'},
      ],
      form: {},
      dialogFormVisible: false,
      urgentFrom: {
        matterId: '',
        dialogContent: '',

      }
    });

    const getList = () => {
      data.loading = true;
      dataScopeMatterList(data.queryParams).then((response) => {
        data.matterList = response.rows;
        data.total = response.total;
        data.loading = false;
      });
    };
    const handleCurrentChange = (currentPage) => {
      data.queryParams.pageNum = currentPage;
      getList();
    };
    const formatDate = (row, column, cellValue) => {
      if (!cellValue) return '';
      const date = new Date(cellValue);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }

    const renderStatus = (row, column, cellValue) => {
      if (row.em1) {
        return row.em1;
      } else {

        const currentDate = new Date();
        const deadlineDate = new Date(row.completionDeadline); // 计划完成时间
        if (currentDate > deadlineDate) {
          return `<span style="color: red;">超时</span>`;
        } else {
          return `<span style="color: blue;">进行中</span>`;
        }
      }
    }


    const getStatusText = (row) => {
      if (row.em1) {
        return row.em1;
      } else {
        const currentDate = new Date();
        const deadlineDate = new Date(row.completionDeadline);
        const summaryDate = row.summaryDate ? new Date(row.summaryDate) : null;

        if (summaryDate) {
          return summaryDate > deadlineDate ? '超时' : '完成';
        } else {
          return currentDate > deadlineDate ? '超时' : '进行中';
        }
      }
    };

    const getStatusColor = (row) => {
      if (row.em1) {
        return 'black';
      } else {
        const currentDate = new Date();
        const deadlineDate = new Date(row.completionDeadline);
        const summaryDate = row.summaryDate ? new Date(row.summaryDate) : null;

        if (summaryDate) {
          return summaryDate > deadlineDate ? 'red' : 'green';
        } else {
          return currentDate > deadlineDate ? 'red' : 'blue';
        }
      }
    };



    const handleQuery = () => {
      data.queryParams.pageNum = 1;
      getList();
    };

    const resetQuery = () => {
      Object.assign(data.queryParams, {
        pageNum: 1,
        pageSize: 10,
        isKeyWork: '', //是否重要工作
        isTimeOut: '', //是否超期
        keyWord: null, // 关键词
        matterName: '',
        em1: null,
        em2: null,
        em3: null,
        em4: null,
        em5: null,
      });
      handleQuery();
    };

    const handleSelectionChange = (selection) => {
      data.ids = selection.map((item) => item.matterId);
      data.single = selection.length !== 1;
      data.multiple = !selection.length;
    };

    /* const getInto = (row) => {
      emit('getInto', row)
    }; */
    const getInto = (row) => {
      router.push({ path: "/matter/tab", query: { ...row } });
    };
    const urgent = (row) => {
      data.urgentFrom.matterId = row.matterId
      data.dialogFormVisible = true
    };
    /* const createMatter = () => {
      emit('createMatter');
    }; */
    /** 创建事项 */
    const createMatter = () => {
      router.push({ path: "/matter/create" });
    }
    // 查看事项操作
    const viewMatter = (row) => {
      emit('seeMatter', row)
    };

    const getIsLeader = (row)=>{
      if (!row.isLeader) {
        return true;
      }
      return row.em4 !== '3';
    }

    // 关注
    const handleSwitchChange = (row) => {
      updateIsFollowed({matterId: row.matterId, isFollowed: row.isFollowed}).then((response) => {
        row.isFollowed = response.data.isFollowed
      })
    };
    // 是否是重要工作
    const handleSwitchChange2 = (row) => {
      // alert(row.isKeyWork)
      updteIsKeyWork({matterId: row.matterId, isKeyWork: row.isKeyWork}).then((response) => {
        getList()
      })
    };
    const handleClose = () => {
      data.urgentFrom.dialogContent = ''
      data.urgentFrom.matterId = ''
      data.dialogFormVisible = false
    };
    const submitDialog = () => {

      if (!data.urgentFrom.dialogContent.trim()) {
        proxy.$modal.msgWarning("请输入催办内容");
        return;
      }

      addDialog(data.urgentFrom).then(res=>{
        if (res.code === 200) {
          proxy.$modal.msgSuccess("催办成功");
          handleClose()
          getList();
        } else {
          proxy.$modal.msgError(res.msg);
        }
      })

    };


    onMounted(() => {
      getList();
    });

    return {
      ...toRefs(data),
      task_status,
      getList,
      handleQuery,
      resetQuery,
      handleSelectionChange,
      getInto,
      urgent,
      createMatter,
      formatDate,
      handleCurrentChange,
      renderStatus,
      getStatusText,
      getStatusColor,
      handleSwitchChange,
      handleSwitchChange2,
      handleClose,
      submitDialog,
      viewMatter,
      getIsLeader,
    };
  },
};
</script>

<style>
</style>
